package com.lxq.smartsign.smartattendance.websocket;

import android.util.Log;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.Buffer;

public class WebSocketHandler extends WebSocketListener {

    private static WebSocketHandler INST;

    private String wsUrl;


    private OkHttpClient client = new OkHttpClient.Builder()
            .build();

    private WebSocketHandler(String wsUrl) {
        this.wsUrl = wsUrl;
    }

    public static WebSocketHandler getInstance(String url) {
        if (INST == null) {
            synchronized (WebSocketHandler.class) {
                INST = new WebSocketHandler(url);
            }
        }

        return INST;
    }

    public void connect() {
        //构造request对象
        Request request = new Request.Builder()
                .url(wsUrl)
                .build();

        client.newWebSocket(request, this);
    }

    public void onOpen(WebSocket webSocket, Response response) {
        Log.e("open","连接成功");
    }

    public void onFailure(IOException e, Response response) {
        Log.e("onFailure","连接失败");
    }

    public void onMessage(ResponseBody message) throws IOException {
        Log.e("onMessage",message.string());
    }

    public void onPong(Buffer payload) {
        Log.e("onPong",payload.readUtf8());
    }

    public void onClose(int code, String reason) {
        Log.e("onClose","code="+code+",reason="+reason);
    }
}
